import sqlite3
import logging
from typing import List, Optional

class BaseModel:
    """ORM基类"""
    @classmethod
    def create_table(cls):
        fields = []
        for attr in cls.__dict__.values():
            if isinstance(attr, tuple):
                # 使用字段定义中的完整SQL语句
                fields.append(attr[0])
        sql = f"CREATE TABLE IF NOT EXISTS {cls.TABLE_NAME} ({', '.join(fields)})"
        return sql

class DatabaseHelper:
    """数据库操作帮助类"""
    def __init__(self, db_path="assets/db/borrow_system.db"):
        self.conn = sqlite3.connect(db_path)
        self.logger = logging.getLogger("database")

    def execute(self, sql: str, params: tuple = None) -> sqlite3.Cursor:
        try:
            cursor = self.conn.cursor()
            if params:
                cursor.execute(sql, params)
            else:
                cursor.execute(sql)
            self.conn.commit()
            return cursor
        except sqlite3.Error as e:
            self.logger.error(f"Database error: {str(e)}")
            raise

    def fetch_all(self, sql: str, params: tuple = None) -> List[dict]:
        cursor = self.execute(sql, params)
        columns = [col[0] for col in cursor.description]
        return [dict(zip(columns, row)) for row in cursor.fetchall()]

    def close(self):
        self.conn.close()
